<template>
  <div class="update-photo">
    <img :src="imgPath" ref="imgRef"/>
    <div class="footer">
      <div @click="onCancel">取消</div>
      <div @click="onConfirm">完成</div>
    </div>
  </div>
</template>

<script>
import 'cropperjs/dist/cropper.css'
import Cropper from 'cropperjs'
import { updateUserAvatar } from '@/api/user'
let cropper
export default {
  name: 'UpdatePhoto',
  props: {
    imgPath: [Object, String]
  },
  data () {
    return {
    }
  },
  components: {},
  created () {},
  mounted () {
    const image = this.$refs.imgRef
    cropper = new Cropper(image, {
      viewMode: 1, // 限制裁剪框不超过画布的大小。
      dragMode: 'move', // 移动画布
      aspectRatio: 1, // 定义裁剪框的固定纵横比。默认情况下，裁剪框有一个自由比例
      autoCropArea: 1, // 它应该是一个介于 0 和 1 之间的数字。定义自动裁剪区域大小（百分比）
      cropBoxMovable: false, // 允许通过拖动来移动裁剪框
      cropBoxResizable: false, // 允许通过拖动来调整裁剪框的大小
      background: false
    })
    console.log(cropper)
  },
  methods: {
    onCancel () {
      this.$emit('close')
    },
    onConfirm () {
      // 获取裁剪结果
      cropper.getCroppedCanvas().toBlob(async (blob) => {
        console.log(blob)
        // 发请求
        const formData = new FormData()
        formData.append('photo', blob)
        const res = await updateUserAvatar(formData)
        // 提示成功
        this.$toast.success('修改成功')
        // 修改数据
        this.$emit('input', res.data.data.photo)
        // 关闭弹层
        this.$emit('close')
      })
    }
  }
}
</script>

<style lang="less" scoped>
.update-photo{
  background-color: black;
  height: 100%;
}
/* Ensure the size of the image fit the container perfectly */
img {
  display: block;

  /* This rule is very important, please don't ignore this */
  max-width: 100%;
}
.footer {
      position: fixed;
    bottom: 0;
    left: 0;
    width: 100%;
    display: flex;
    justify-content: space-between;
    font-size: 36px;
    padding: 20px;
    box-sizing: border-box;
    color: #fff;
}
</style>
